package logic

import (
	"context"
	"fmt"
	"sync"
	"time"

	"go-papers/constant"
	"go-papers/models"
	"go-papers/notice"
	"go-papers/pkg/lognew"
	"go-papers/tools"
)

func CleanOrderByList(doc []models.Order) {
	for _, v := range doc {
		v.OrderStatus = "0"
		_, err := v.Delete(v.OrderId)
		if err != nil {
			lognew.Error(context.TODO(), "CleanOrderByList", lognew.Fields{"order": v, "err": err.Error()})
		}
	}
}

func SureOrderByList(doc []models.Order) {
	c := context.TODO()

	for _, v := range doc {

		//操作状态变动
		v.OrderStatus = constant.ORDER_STATUS_20
		v.SureTime = time.Now().Format("2006-01-02 15:04:05")
		v.IsSure = "1"
		_, err := v.Update(v.OrderId)
		if err != nil {
			lognew.Error(c, "SureOrderByList", lognew.Fields{"order": v, "err": err.Error()})
			continue
		}

		// 处理订单分账 以及 分账佣金记录
		if ok, msg := OrderShareHandle(v.OrderId); !ok {
			lognew.Error(c, "SureOrderByList", lognew.Fields{"order": v, "err": msg})
			return
		}

		//用户操作订单记录
		orlog := models.OrderOprateLog{
			OrderId:         v.OrderId,
			Title:           "系统自动确认排课",
			Desc:            "系统自动确认排课/" + fmt.Sprintf("%.2f", v.OrderPrice),
			LogType:         "5",
			OrderStatusName: tools.OrderStatusName(v.OrderStatus),
			PayStatusName:   tools.PayStatusName(v.PayTime, v.RefundTime),
			LogName:         "系统自动确认排课",
			LogUid:          v.MemberId,
		}
		_, _ = orlog.Create() // 用户确认排课

		var wg sync.WaitGroup //定义一个同步等待的组
		wg.Add(1)             //为同步等待组增加一个成员
		go func() {

			notice.NoticeByType(notice.OrderSureSuccess, v.OrderId, v.MemberId, 0) // 用户 用户确认排课

			OrderChangeInfo(v.OrderId) //自动排课

			defer wg.Done()
		}()

		wg.Wait()
		fmt.Println("WE DONE!!!")

	}
}
